import {
  setItem,
  getItem
} from "common/localStorage"

export default {
  state: () => ({
    prodArr: [{
      "img": "https://m.360buyimg.com/mobilecms/s300x300_jfs/t1/35480/40/16027/198529/60ae276eE1b1985f4/465e3893d32f4de5.jpg!q70.dpg.webp",
      "price": 9.9,
      "name": "适用华为Type-c数据线快充5A手机充电器线p20p30pro mate30/40荣耀安卓小米承简 【5A超级快充】type-c闪充线【1米2条】",
      "brandId": 448574,
      "num": 2
    }]
  }),
  getters: {
    totalProd(state) {
      let countM = 0;
      for (let i = 0; i < state.prodArr.length; i++) {
        const prod = state.prodArr[i];
        countM += Number(prod.price) * Number(prod.num);
      }
      return countM.toFixed(2);
    },
    countNum(state) {
      let count = 0;
      state.prodArr.forEach(prod => {
        count += Number(prod.num);
      });
      return count;
    }
  },
  mutations: {
    addCart(state, payload) {
      let flag = false;

      for (let i = 0; i < state.prodArr.length; i++) {
        const item = state.prodArr[i];
        if (item.brandId == payload.brandId) {
          flag = i + "";
        }
      }
      if (typeof flag == "string") {
        state.prodArr[Number(flag)].num++;
      } else {
        state.prodArr.splice(0, 0, payload);
      }
    },
    addNum(state, id) {
      state.prodArr.forEach(prod => {
        prod.brandId == id ? prod.num++ : false;
      });
    },
    reduceNum(state, id) {
      state.prodArr.forEach(prod => {
        prod.brandId == id ? (prod.num > 1 ? prod.num-- : prod.num) : false;
      });
    },
    saveCart(state) {
      let jsonCart = JSON.stringify(state.prodArr);
      setItem("cart", jsonCart);
    },
    getCart(state){
      let cart = getItem("cart");
      if (cart != null) {
        state.prodArr = JSON.parse(cart);
      }
    }
  },
}